<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <v-header></v-header>
        <v-list :tasks="tasks" v-if="tasks.length"></v-list>
        <div class="noTask" v-else>no task</div>
        <v-footer :tasks="tasks"></v-footer>
      </div>
    </div>
  </div>
</template>

<script>
import header from './components/header';
import footer from './components/footer';
import list from './components/list';
export default {
  name: 'App',
  data() {
    return {
      tasks: [
        // { id: 0, checked: false, content: '给冬雨刷牙' },
        // { id: 1, checked: false, content: '叫冬雨起床' },
        // { id: 2, checked: false, content: '给冬雨盖被子' },
        // { id: 3, checked: false, content: '提醒达姆吃药' },
      ],
    };
  },
  methods: {
    //新增任务
    addTask(task) {
      this.tasks.unshift(task);
    },
    //删除任务
    delTask(id) {
      this.tasks = this.tasks.filter((task) => id !== task.id);
    },
    //切换任务的选中状态
    checkedC({ id, checked }) {
      this.tasks.forEach((task) => {
        if (+task.id === +id) {
          task.checked = checked;
        }
      });
    },
    //清除已完成任务
    clear() {
      this.tasks = this.tasks.filter((task) => !task.checked);
    },
    //全选&全不选
    checkAll(checked) {
      this.tasks.forEach((task) => {
        task.checked = checked;
      });
    },
  },
  components: {
    'v-header': header,
    'v-footer': footer,
    'v-list': list,
  },
  mounted() {
    this.$bus.$on('addTask', this.addTask);
    this.$bus.$on('delTask', this.delTask);
    this.$bus.$on('checkedC', this.checkedC);
    this.$bus.$on('clear', this.clear);
    this.$bus.$on('checkAll', this.checkAll);

    //从localStorage读取todo-tasks 反序列化 覆盖this.tasks
    let tasks = localStorage.getItem('todo-tasks');
    if (tasks) {
      this.tasks = JSON.parse(tasks);
    } else {
      this.tasks = [];
    }
  },
  watch: {
    tasks: {
      handler(tasks) {
        //将tasks任务序列号 存到离线存储中
        localStorage.setItem('todo-tasks', JSON.stringify(tasks));
      },
      deep: true, //开启深度监听
    },
  },
};
</script>

<style scoped>
/*damu add*/
.noTask {
  height: 80px;
  border: 1px solid hotpink;
  text-align: center;
  line-height: 80px;
}
/*damu add*/

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
